<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-button type="primary" @click="addCate">添加分类</el-button>

      <!-- 引入的树形表格插件 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        border
        show-index
        index-text="#"
        :selection-type="false"
        :expand-type="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            :class="[
              scope.row.cat_deleted
                ? ['el-icon-error', 'red']
                : ['el-icon-success', 'green'],
            ]"
          ></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">{{
          scope.row.cat_level + 1
        }}</template>

        <!-- 操作 -->
        <template slot="operation" slot-scope="scope">
          <el-button type="text" @click="edit(scope.row)">编辑</el-button>
          <el-button type="text" @click="del(scope.row)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[3, 6, 10, 15, 30]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类dialog -->
    <el-dialog
      title="添加分类"
      @close="clearForm"
      :visible.sync="addCateVisible"
      width="50%"
    >
      <!-- form表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            v-model="selectedValue"
            :options="fatherCateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑dailog -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateVisible"
      width="50%"
      @close="clearEditForm"
    >
      <el-form :model="editCateForm" label-width="100px">
        <el-form-item label="分类名称:">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="editBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryData: {
        type: 3,
        pagenum: 1,
        pagesize: 6,
      },
      cateList: [],
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          // 表示将当前列定义为模板类
          type: "template",
          // 表示当前这一列使用模板的名称
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "operation",
        },
      ],
      addCateVisible: false,
      editCateVisible: false,

      // 添加分类的表单数据对象
      addCateForm: {
        cat_name: "",
        // 父级分类的id
        cat_pid: 0,
        // 分类的等级，默认要添加的是1级分类
        cat_level: 0,
      },
      editCateForm: {
        cat_name: "",
        cat_id: 0,
      },
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 父级分类列表
      fatherCateList: [],
      // el-cascader的props绑定的
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 选中的父级分类的id数组
      selectedValue: [],
    };
  },
  methods: {
    async getList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryData,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryData.pagesize = newSize;
      this.getList();
    },
    // 监听pagenum改变的事件
    handleCurrentChange(newPageNum) {
      this.queryData.pagenum = newPageNum;
      this.getList();
    },
    // 添加分类按钮
    addCate() {
      this.getFatherCate();
      this.addCateVisible = true;
    },
    // 添加分类中获取父级分类
    async getFatherCate() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类失败");
      }

      this.fatherCateList = res.data;
    },
    // 选中项发生变化是触发
    handleChange() {
      if (this.selectedValue.length > 0) {
        this.addCateForm.cat_pid =
          this.selectedValue[this.selectedValue.length - 1];
        this.addCateForm.cat_level = this.selectedValue.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    // 清楚添加分类表单
    clearForm() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedValue = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    // 添加分类确定按钮
    addCateBtn() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("创建失败");
        }
        this.$message.success("创建成功");
        this.getList();
        this.addCateVisible = false;
      });
    },
    // 编辑操作
    edit(row) {
      this.editCateForm.cat_name = row.cat_name;
      this.editCateForm.cat_id = row.cat_id;
      this.editCateVisible = true;
    },
    // 清空编辑表单
    clearEditForm() {
      this.editCateForm.cat_name = "";
      this.editCateForm.cat_id = 0;
    },
    // 编辑确认按钮
    async editBtn() {
      const { data: res } = await this.$http.put(
        "categories/" + this.editCateForm.cat_id,
        this.editCateForm
      );
      if (res.meta.status !== 200) {
        return this.$message.error("更新失败");
      }
      this.$message.success("更新成功");
      this.getList();
      this.editCateVisible = false;
    },
    // 删除操作
    del(row) {
      this.$confirm("确定删除此分类吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            "categories/" + row.cat_id
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功");
          this.getList();
        })
        .catch(() => {});
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 15px;
}
.green {
  color: green;
}
.red {
  color: red;
}
.el-cascader {
  width: 100%;
}
</style>